package com.sudo.api.config;

import com.sudo.common.component.Ip2RegionProperties;
import com.sudo.common.ip2region.Ip2RegionStrategy;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.util.ResourceUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @Author：DayDayUp
 * @Create：2023/2/6 9:26
 */
@AutoConfiguration
@ConditionalOnClass(Ip2RegionStrategy.class)
@EnableConfigurationProperties(Ip2RegionProperties.class)
@ConditionalOnProperty(prefix = Ip2RegionProperties.PREFIX, name = "enabled", havingValue = "true")
public class Ip2RegionAutoConfiguration {

    @Resource
    private Ip2RegionProperties ip2RegionProperties;

    @Bean
    public Ip2RegionStrategy ip2RegionStrategy() throws FileNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<? extends Ip2RegionStrategy> strategy = ip2RegionProperties.getStrategy();
        Constructor<? extends Ip2RegionStrategy> constructor = strategy.getConstructor(String.class);
        String dbFile = ip2RegionProperties.getDbFile();
        File file = ResourceUtils.getFile(dbFile);
        return constructor.newInstance(file.getAbsolutePath());
    }
}
